﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.AspNetCore.Http;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using Extentions;
using TrainingReminderSystem.Model;
using TrainingReminderSystem.Dal;
using System.Threading.Tasks;

namespace TrainingReminderSystem.Bll
{
    /// <summary>
    /// 意见反馈 逻辑层
    /// </summary>
    public partial class SysFeedbackBll : PcLoginedBll
    {
        #region 添加和编辑的时候 验证数据和设置默认值

        /// <summary>
        /// 添加和编辑的时候 验证数据和设置默认值
        /// </summary>
        /// <param name="model"></param>
        /// <param name="isAdd">添加还是编辑,可以不管此参数</param>/// <param name="db"></param>
        /// <returns>是否通过,true表示验证通过,false代表验证没有通过</returns>
        public AjaxResult<dynamic> Validate(SysFeedback model, bool isAdd, DbEntities db)
        {
            var r = new AjaxResult<dynamic>();
            if (model == null)
            {
                r.Message = LanguageHelper.NoSubmitData;
                return r;
            }
            model.ExTrimProperty();
            r = ValidatePartial(model, isAdd, r, db);
            if (r.Success == false) return r;
            r.Success = false;

            if (string.IsNullOrEmpty(model.Describe))
            {
                r.Message = LanguageHelper.RequireString1<SysFeedback>(nameof(SysFeedback.Describe));
                return r;
            }
            model.FileUrl = Base64Helper.SaveFileFromBase64(model.FileUrl);
            model.ImageUrl1 = Base64Helper.SaveFileFromBase64(model.ImageUrl1);
            model.ImageUrl2 = Base64Helper.SaveFileFromBase64(model.ImageUrl2);
            model.ImageUrl3 = Base64Helper.SaveFileFromBase64(model.ImageUrl3);
            model.ImageUrl4 = Base64Helper.SaveFileFromBase64(model.ImageUrl4);
            model.ImageUrl5 = Base64Helper.SaveFileFromBase64(model.ImageUrl5);

            if (isAdd)
            {
                if (SysConfig.EnumRunProject == EnumRunProject.系统后台端)
                {
                    model.SysStoreID = CurrentStore.SysStoreID;
                }
                if (SysConfig.EnumRunProject == EnumRunProject.微信客户端)
                {
                    model.SysStoreID = CustomerLoginedBll.CurrentStore.SysStoreID;
                }

                model.CreateDate = DateTime.Now;
            }

            r.Success = true;
            return r;
        }

        #endregion

        #region 保存数据

        /// <summary>
        /// 保存数据
        /// </summary>
        /// <param name="model">保存的对象,成功之后model对象的model对象的主键能得到对象</param>
        /// <returns></returns>
        public async Task<AjaxResult<dynamic>> Save(SysFeedback model)
        {
            using (var db = Db)
            {
                return await Save(model, db);
            }
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        /// <param name="model">保存的对象,成功之后model对象的model对象的主键能得到对象</param>
        /// <returns></returns>
        internal async Task<AjaxResult<dynamic>> Save(SysFeedback model, DbEntities db)
        {
            if (this.SaveJudgePartial(model, db))
            {
                return await Add(model, db);
            }
            return await Modify(model, db);
        }

        #endregion

        #region 分页方法

        /// <summary>
        /// 查询条件,能替换掉一些属性查询为自定义查询
        /// </summary>
        /// <param name="where"></param>
        /// <param name="key"></param>
        /// <param name="val"></param>
        /// <param name="db"></param>
        /// <returns></returns>
        private Expression<Func<SysFeedback, bool>> InitSearchDelegete(Expression<Func<SysFeedback, bool>> where, string key, string val, DbEntities db)
        {
            var r = InitSearchDelegetePartial(where, key, val, db);
            if (r != null) return r;
            return null;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="index"></param>
        /// <param name="size"></param>
        /// <param name="form"></param>
        /// <param name="sortField"></param>
        /// <param name="asc"></param>
        /// <returns></returns>
        public async Task<AjaxResult<dynamic>> GetListByPage(int index, int size, IFormCollection form = null, string sortField = "", bool asc = false)
        {
            using (var db = Db)
            {
                Expression<Func<SysFeedback, bool>> where = InitSearch<SysFeedback, DbEntities>(form, InitSearchDelegete, db); //拼接查询条件方法
                IQueryable<SysFeedback> query = OrderByPartial(db.SysFeedback, sortField, asc, db);
                int counts;
                var tempIDList = query.ExGetListByPage(index, size, out counts, where).Select(m => m.SysFeedbackID);
                var r = new AjaxResult<dynamic>();
                r.Total = counts;
                IQueryable<SysFeedback> list = query.AsNoTracking().Where(m => tempIDList.Contains(m.SysFeedbackID));
                var tempList = list.Select(m => new
                {
                    SysFeedbackID = m.SysFeedbackID,
                    EnumRunProject = m.EnumRunProject,
                    SysStoreID = m.SysStoreID,
                    SysStore = new
                    {
                        SysStoreID = (int?)m.SysStore.SysStoreID,
                        EnumSysStoreType = (EnumSysStoreType?)m.SysStore.EnumSysStoreType,
                        SysStoreName = m.SysStore.SysStoreName,
                        PhoneNumber = DbFun.fn_replaceNum(m.SysStore.PhoneNumber, CanSeePhone),
                        EnumStatus = (EnumStatus?)m.SysStore.EnumStatus
                    },
                    SysEmployeeID = m.SysEmployeeID,
                    SysEmployee = new
                    {
                        SysEmployeeID = (int?)m.SysEmployee.SysEmployeeID,
                        EnumQuitStatus = (EnumQuitStatus?)m.SysEmployee.EnumQuitStatus,
                        SysEmployeeName = m.SysEmployee.SysEmployeeName,
                        SysEmployeePhone = DbFun.fn_replaceNum(m.SysEmployee.SysEmployeePhone, CanSeePhone),
                        CanSeePhone = (bool?)m.SysEmployee.CanSeePhone
                    },
                    SysCustomerID = m.SysCustomerID,
                    SysCustomer = new
                    {
                        SysCustomerID = (int?)m.SysCustomer.SysCustomerID,
                        EnumSysCustomerType = (EnumSysCustomerType?)m.SysCustomer.EnumSysCustomerType,
                        SysCustomerName = m.SysCustomer.SysCustomerName,
                        Phone = DbFun.fn_replaceNum(m.SysCustomer.Phone, CanSeePhone),
                        EnumStatus = (EnumStatus?)m.SysCustomer.EnumStatus
                    },
                    //SysCustomerOpenID = m.SysCustomerOpenID,
                    SysCustomerOpenID = db.SysCustomerOpenID.Where(n => n.ID == m.SysCustomerOpenID).Select(n => new
                    {
                        n.OpenID,
                        n.nickname,
                        n.headimgurl,
                        n.CreateDate
                    }).FirstOrDefault(),

                    Describe = m.Describe,
                    FileUrl = m.FileUrl,
                    ImageUrl1 = m.ImageUrl1,
                    ImageUrl2 = m.ImageUrl2,
                    ImageUrl3 = m.ImageUrl3,
                    ImageUrl4 = m.ImageUrl4,
                    ImageUrl5 = m.ImageUrl5,
                    EnumDealStatus = m.EnumDealStatus,
                    CreateDate = m.CreateDate,
                    Remark = m.Remark,

                    Count = m.SysFeedbackRecord.Count()
                });
                var resultList = await tempList.ToListAsync();
                r.Success = true;
                r.Result = resultList;
                return r;
            }
        }

        #endregion

        #region 得到单对象,返回值有可能为null

        /// <summary>
        /// 得到单对象,返回值有可能为null
        /// </summary>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        public async Task<AjaxResult<SysFeedback>> GetModel(int id)
        {
            using (var db = Db)
            {
                return await GetModel(id, db);
            }
        }

        internal async Task<AjaxResult<SysFeedback>> GetModel(int id, DbEntities db)
        {
            string include = GetModelIncludePartial();
            IQueryable<SysFeedback> query = !string.IsNullOrWhiteSpace(include) ? db.SysFeedback.Include(include) : db.SysFeedback;
            var temp = query.AsNoTracking().Where(m => m.SysFeedbackID == id);
            var dbModel = await temp.FirstOrDefaultAsync();
            return GetModelReturnPartial(dbModel, db);
        }

        #endregion

        #region 添加数据

        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="model">添加的对象,成功之后model对象的主键能得到对象</param>
        /// <returns></returns>
        public async Task<AjaxResult<dynamic>> Add(SysFeedback model)
        {
            using (var db = Db)
            {
                return await Add(model, db);
            }
        }

        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="model">添加的对象,成功之后model对象的主键能得到对象</param>
        /// <param name="db"></param>
        /// <returns></returns>
        internal async Task<AjaxResult<dynamic>> Add(SysFeedback model, DbEntities db)
        {
            var r = new AjaxResult<dynamic>() { Success = false };
            if (db == null) db = Db;
            var tempAr = Validate(model, true, db);
            if (tempAr.Success == false)
            {
                r.Message = tempAr.Message;
                r.Result = tempAr.Result;
                r.Total = tempAr.Total;
                return r;
            }
            var tran = db.Database.CurrentTransaction;
            bool hasTran = tran != null;
            if (hasTran == false) tran = await db.Database.BeginTransactionAsync();
            try
            {
                db.SysFeedback.Add(model);
                string error = AddLog(db, model, EnumLogType.新建);
                if (!string.IsNullOrEmpty(error))
                {
                    return AjaxResult<dynamic>.ErrorResult(error);
                }
                await db.SaveChangesAsync();
                r = AddUpdateSuccessPartial(model, true, r, db);
                if (r.Success == false)
                {
                    return r;
                }
                await db.SaveChangesAsync();
                if (hasTran == false)
                {
                    await tran.CommitAsync();
                    await tran.DisposeAsync();
                    tran = null;
                }
                r.Success = true;
                r.Message = LanguageHelper.Success;
                r.Result = model;
                return r;
            }
            catch (Exception ex)
            {
                ex.ExLogError(GetCurrentOther());
                r.Total = (int)EnumTotal.异常;
                r.Success = false;
                r.Message = string.Format(LanguageHelper.Fail1, ex.ExMessageWithInner());
                return r;
            }
            finally
            {
                if (hasTran == false && tran != null)
                {
                    await tran.RollbackAsync();
                    await tran.DisposeAsync();
                    tran = null;
                }
            }
        }

        #endregion

        #region 编辑Old

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="model">添加的对象,成功之后model对象的主键能得到对象</param>
        /// <returns></returns>
        public async Task<AjaxResult<dynamic>> Update(SysFeedback model)
        {
            using (var db = Db)
            {
                return await Update(model, db);
            }
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="model">添加的对象,成功之后model对象的主键能得到对象</param>
        /// <param name="db"></param>
        /// <returns></returns>
        internal async Task<AjaxResult<dynamic>> Update(SysFeedback model, DbEntities db)
        {
            var r = new AjaxResult<dynamic>() { Success = false };
            if (db == null) db = Db;
            var tempAr = Validate(model, false, db);
            if (tempAr.Success == false)
            {
                r.Message = tempAr.Message;
                r.Result = tempAr.Result;
                r.Total = tempAr.Total;
                return r;
            }
            var tran = db.Database.CurrentTransaction;
            bool hasTran = tran != null;
            if (hasTran == false) tran = await db.Database.BeginTransactionAsync();
            try
            {
                var dbModel = await db.SysFeedback.FirstOrDefaultAsync(m => m.SysFeedbackID == model.SysFeedbackID);
                if (dbModel == null)
                {
                    r.Message = LanguageHelper.NoData;
                    return r;
                }

                dbModel.EnumRunProject = model.EnumRunProject;
                dbModel.SysEmployeeID = model.SysEmployeeID;
                dbModel.SysCustomerID = model.SysCustomerID;
                dbModel.SysCustomerOpenID = model.SysCustomerOpenID;
                dbModel.Describe = model.Describe;
                dbModel.FileUrl = model.FileUrl;
                dbModel.ImageUrl1 = model.ImageUrl1;
                dbModel.ImageUrl2 = model.ImageUrl2;
                dbModel.ImageUrl3 = model.ImageUrl3;
                dbModel.ImageUrl4 = model.ImageUrl4;
                dbModel.ImageUrl5 = model.ImageUrl5;
                dbModel.EnumDealStatus = model.EnumDealStatus;
                dbModel.Remark = model.Remark;

                string error = AddLog(db, model, EnumLogType.编辑);
                if (!string.IsNullOrEmpty(error))
                {
                    return AjaxResult<dynamic>.ErrorResult(error);
                }
                await db.SaveChangesAsync();
                r = AddUpdateSuccessPartial(model, false, r, db, dbModel);
                if (r.Success == false)
                {
                    return r;
                }
                await db.SaveChangesAsync();
                if (hasTran == false)
                {
                    await tran.CommitAsync();
                    await tran.DisposeAsync();
                    tran = null;
                }
                r.Success = true;
                r.Message = LanguageHelper.Success;
                r.Result = dbModel;
                return r;
            }
            catch (Exception ex)
            {
                ex.ExLogError(GetCurrentOther());
                r.Total = (int)EnumTotal.异常;
                r.Success = false;
                r.Message = string.Format(LanguageHelper.Fail1, ex.ExMessageWithInner());
                return r;
            }
            finally
            {
                if (hasTran == false && tran != null)
                {
                    await tran.RollbackAsync();
                    await tran.DisposeAsync();
                    tran = null;
                }
            }
        }

        #endregion

        #region 编辑New

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="model">添加的对象,成功之后model对象的主键能得到对象</param>
        /// <returns></returns>
        public async Task<AjaxResult<dynamic>> Modify(SysFeedback model)
        {
            using (var db = Db)
            {
                return await Modify(model, db);
            }
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="model">添加的对象,成功之后model对象的主键能得到对象</param>
        /// <param name="db"></param>
        /// <returns></returns>
        internal async Task<AjaxResult<dynamic>> Modify(SysFeedback model, DbEntities db)
        {
            var r = new AjaxResult<dynamic>() { Success = false };
            if (db == null) db = Db;
            var tempAr = Validate(model, false, db);
            if (tempAr.Success == false)
            {
                r.Message = tempAr.Message;
                r.Result = tempAr.Result;
                r.Total = tempAr.Total;
                return r;
            }
            var tran = db.Database.CurrentTransaction;
            bool hasTran = tran != null;
            if (hasTran == false) tran = await db.Database.BeginTransactionAsync();
            try
            {
                ModifyBasePartial(model, db, typeof(SysFeedback));

                string error = AddLog(db, model, EnumLogType.编辑);
                if (!string.IsNullOrEmpty(error))
                {
                    return AjaxResult<dynamic>.ErrorResult(error);
                }
                await db.SaveChangesAsync();
                r = AddUpdateSuccessPartial(model, false, r, db);
                if (r.Success == false)
                {
                    return r;
                }
                await db.SaveChangesAsync();
                if (hasTran == false)
                {
                    await tran.CommitAsync();
                    await tran.DisposeAsync();
                    tran = null;
                }
                r.Success = true;
                r.Message = LanguageHelper.Success;
                r.Result = model;
                return r;
            }
            catch (Exception ex)
            {
                ex.ExLogError(GetCurrentOther());
                r.Total = (int)EnumTotal.异常;
                r.Success = false;
                r.Message = string.Format(LanguageHelper.Fail1, ex.ExMessageWithInner());
                return r;
            }
            finally
            {
                if (hasTran == false && tran != null)
                {
                    await tran.RollbackAsync();
                    await tran.DisposeAsync();
                    tran = null;
                }
            }
        }

        #endregion

        #region 删除

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<AjaxResult<dynamic>> Del(int id)
        {
            using (var db = Db)
            {
                return await Del(id, db);
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <param name="db"></param>
        /// <returns></returns>
        internal async Task<AjaxResult<dynamic>> Del(int id, DbEntities db)
        {
            var r = new AjaxResult<dynamic>() { Success = false };
            if (db == null) db = Db;
            var tran = db.Database.CurrentTransaction;
            bool hasTran = tran != null;
            if (hasTran == false) tran = await db.Database.BeginTransactionAsync();
            try
            {
                var dbModel = await db.SysFeedback.FirstOrDefaultAsync(m => m.SysFeedbackID == id);
                if (dbModel == null)
                {
                    r.Message = LanguageHelper.NoData;
                    return r;
                }

                r = DelValidatePartial(dbModel, r, db);
                if (r.Success == false)
                {
                    return r;
                }
                db.SysFeedback.Remove(dbModel);
                string error = AddLog(db, dbModel, EnumLogType.删除);
                if (!string.IsNullOrEmpty(error))
                {
                    return AjaxResult<dynamic>.ErrorResult(error);
                }
                await db.SaveChangesAsync();
                r = DelSuccessPartial(dbModel, r, db);
                if (r.Success == false)
                {
                    return r;
                }
                await db.SaveChangesAsync();
                if (hasTran == false)
                {
                    await tran.CommitAsync();
                    await tran.DisposeAsync();
                    tran = null;
                }
                r.Success = true;
                r.Message = LanguageHelper.Success;
                return r;
            }
            catch (Exception ex)
            {
                ex.ExLogError(GetCurrentOther());
                r.Total = (int)EnumTotal.异常;
                r.Success = false;
                r.Message = string.Format(LanguageHelper.Fail1, ex.ExMessageWithInner());
                return r;
            }
            finally
            {
                if (hasTran == false && tran != null)
                {
                    await tran.RollbackAsync();
                    await tran.DisposeAsync();
                    tran = null;
                }
            }
        }

        #endregion

        //#region 导入
        //#endregion
    }
}
